package com.cjh.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjh.common.dto.UserRoleDTO;
import com.cjh.common.entity.User;
import com.cjh.common.entity.UserRole;
import com.cjh.common.mapper.UserRoleMapper;
import com.cjh.common.response.Result;
import com.cjh.common.service.UserService;
import com.cjh.common.mapper.UserMapper;
import com.cjh.common.utils.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Override
    public User getUserByUserName(String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        return user;
    }
    @Override
    public Result getUserByLikeUsername(Page<User> page, String username) {
        if(!username.isEmpty()){
            LambdaQueryWrapper<User> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
            objectLambdaQueryWrapper.like(User::getUsername,username);
            Page<User> userPage = userMapper.selectPage(page, objectLambdaQueryWrapper);
            return new Result().setCode(200).setMessage("操作成功！").setData(userPage);
        }else{
            Page<User> userPage = userMapper.selectPage(page, null);
            return new Result().setCode(200).setMessage("操作成功！").setData(userPage);
        }
    }

    @Override
    public UserRoleDTO getUserById(Integer id) {
        return userMapper.selectUserRoleDTOByUserId(id);
    }
    public User getUserByUsername(String username){
        LambdaQueryWrapper<User> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
        objectLambdaQueryWrapper.eq(User::getUsername,username);
        return userMapper.selectOne(objectLambdaQueryWrapper);
    }
    @Override
    public Result addUser(UserRoleDTO userRoleDTO) {
        if(userRoleDTO.getRoleNameIdList().size() == 0){
            return new Result().setCode(201).setMessage("角色不能为空！");
        }
        if(getUserByUsername(userRoleDTO.getUsername()) != null){
            return new Result().setCode(201).setMessage("用户名已经存在！");
        }
        User user = new User();
        BeanUtils.copyProperties(userRoleDTO,user);
        String s = StringUtil.generateUUID();
        user.setSalt(s);
        user.setPassword(StringUtil.md5("123456"+s));
        int insert = userMapper.insert(user);
        if(insert == 0){
            return new Result().setCode(201).setMessage("增加用户失败，请重试！");
        }
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getUserId());
        for(Integer r : userRoleDTO.getRoleNameIdList()){
            userRole.setRoleId(r);
            userRoleMapper.insert(userRole);
        }
        return new Result().setCode(200).setMessage("操作成功！");
    }

    @Override
    public Result updateUser(UserRoleDTO userRoleDTO) {
        UserRoleDTO dbUserRoleDTO = getUserById(userRoleDTO.getUserId());
        Set<Integer> add = new HashSet<>();
        add.addAll(userRoleDTO.getRoleNameIdList());
        add.removeAll(dbUserRoleDTO.getRoleNameIdList());
        Set<Integer> reduce = new HashSet<>();
        reduce.addAll(dbUserRoleDTO.getRoleNameIdList());
        reduce.removeAll(userRoleDTO.getRoleNameIdList());
        User user = new User();
        BeanUtils.copyProperties(userRoleDTO,user);
        userMapper.updateById(user);
        for (Integer a: add){
            userRoleMapper.insert(new UserRole(user.getUserId(),a));
        }
        for (Integer r: reduce){
            userRoleMapper.delete(Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId,user.getUserId()).eq(UserRole::getRoleId,r));
        }
        return new Result().setCode(200).setMessage("修改成功！");
    }

    @Override
    public Result updateUserPassword(Integer id, String password) {
        User user = userMapper.selectById(id);
        user.setPassword(StringUtil.md5(password+user.getSalt()));
        userMapper.updateById(user);
        return new Result().setCode(200).setMessage("操作成功！");
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result deleteUserById(Integer id) {
        try {
            if(id==1){
                return new Result().setCode(201).setMessage("admin用户无法删除！");
            }
            userRoleMapper.delete(Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId,id));
            userMapper.deleteById(id);
            return new Result().setCode(200).setMessage("删除成功！");
        }catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new Result().setCode(202).setMessage(e.getMessage());
        }
    }
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result deleteUserByIdList(List<Integer> list) {
        try {
            int i = list.indexOf(1);
            if( i != -1){
                list.remove(i);
                for (Integer id:list){
                    userRoleMapper.delete(Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId,id));
                }
                userMapper.deleteBatchIds(list);
                return new Result().setCode(200).setMessage("admin用户无法删除,其他用户删除成功！");
            }else{
                for (Integer id:list){
                    userRoleMapper.delete(Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId,id));
                }
                userMapper.deleteBatchIds(list);
                return new Result().setCode(200).setMessage("操作成功！");
            }
        }catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new Result().setCode(202).setMessage(e.getMessage());
        }
    }
}




